package com.dyz.leetcode;


import java.util.Stack;

public class LongestValidParentheses32 {
    public static void main(String[] args) {
        int i = new LongestValidParentheses32().longestValidParentheses(")()");
        System.out.println(i);
    }
    public int longestValidParentheses(String s) {
            int max = 0;
            int start = 0;//不匹配的位置
            if(null == s) return 0;

            int len = s.length();

            Stack<Integer> stack = new Stack<>();
            for(int index = 0; index < len; index++){
                //遇左括号(，压栈(栈中元素为当前位置所处的下标)
                if('(' == s.charAt(index)){
                    stack.push(index);
                } else {
                    if(stack.isEmpty()){
                        start = index+1;
                    } else {
                        stack.pop();
                        if(stack.isEmpty()){
                            max = Math.max(max, index-start+1);
                        } else {
                            max = Math.max(max, index-stack.peek());
                        }
                    }
                }
            }
            return max;
        }

}
